package com.bodacn.keypoint;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StyleInfoActivity extends AppCompatActivity implements View.OnClickListener, View.OnFocusChangeListener, View.OnLongClickListener {
    private String TAG=this.getClass().getName();
    private final int MSG_DepartOver=1001;
    private final int MSG_OrderOver =1002;
    private final int MSG_POOver =1003;
    private final int MSG_DetailOver=1004;
    private final int MSG_FocusDefaultItem =1005;
    private final int MSG_GetArrangeOver =1006;
    Button btn_Refresh,btn_Return,btn_find;
    ListView orderList, arrangeList;
    EditText edt_barcode,edt_OrderNO;
    JSONArray orderJson,arrangeJson;
    String STORE_NAME = "Settings";
    String curLoginUserNo,curLoginUser,curServiceUrl="",curServiceDir="",curWorkDate="",curDepartNo,curDepart,CPUID;
    String selOrderNo="",selStyleSort="";
    String selFactory="";
    String FormType="SEW";
    Boolean ViewFactory=false;
    View tmpItemView;
    View tmpEdit;
    int tmpItemIndex=-1;
    //拦截扫描枪输入部分
    String WorkSection="";
    String BarcodeStr="";
    ScannerManager scannerManager;

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        return scannerManager.dispatchKeyEvent(event);
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_styleinfo);
        //获取登陆参数
        Bundle paramBundle = this.getIntent().getExtras();
        curLoginUserNo=paramBundle.getString("LoginUserNo");
        curLoginUser=paramBundle.getString("LoginUser");
        curDepartNo=paramBundle.getString("CurDepartNo");
        curDepart=paramBundle.getString("CurDepart");
        curServiceUrl=paramBundle.getString("ServiceUrl");
        curServiceDir=paramBundle.getString("ServiceDir");
        FormType=paramBundle.getString("FormType");
        CPUID=paramBundle.getString("CPUID");
        curWorkDate=paramBundle.getString("WorkDate");
        WorkSection=paramBundle.getString("WorkSection","SEW");
        ViewFactory=paramBundle.getBoolean("ViewFactory",ViewFactory);
        InitView();
        //拦截扫描事件
        scannerManager = new ScannerManager(new ScannerManager.OnScanListener() {
            @Override
            public void onResult(String code,String deviceName) {
                Log.d(TAG, "code= " + code);
                searchBarcodeData(code,"");
                playRingtone();
            }
        },this);

    }

    //刷新缸布列表;
    private void searchBarcodeData(String BarcodeParam,String OrderNoParam)
    {

        String SqlComm = "Exec ScenePAD_GetExtStyleList @Barcode='" + BarcodeParam+"',@StyleNo='" + OrderNoParam
                + "',@DepartNo='" + curDepartNo+ "',@OPERTYPE='STYLEINFO',@UserNo='" + curLoginUserNo + "',@CPUID='" + CPUID + "'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }

    //刷新缸布列表;
    private void getArrange()
    {
        //执行SQL过程
        String SqlComm="Exec ScenePAD_DaliyGetArrange @OperType='GetArrange',@DepartmentNo='" + curDepartNo+ "',@StartDate='"+curWorkDate+ "',@WorkSection='"+WorkSection+"',@UserNo='"+curLoginUserNo+"',@CPUID='"+CPUID+"'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }
    //插放音乐;
    private void playRingtone(){
        Uri notification = Uri.parse("android.resource://"+this.getPackageName()+"/"+R.raw.scan);
        Ringtone r = RingtoneManager.getRingtone(this, notification);
        r.play();

    }

    //初始化;
    public void InitView(){
        edt_barcode=findViewById(R.id.edt_barcode);
        edt_barcode.setInputType(InputType.TYPE_NULL);
        edt_barcode.setOnFocusChangeListener(this);
        edt_OrderNO=findViewById(R.id.edt_OrderNO);
        edt_OrderNO.setInputType(InputType.TYPE_NULL);
        edt_OrderNO.setOnFocusChangeListener(this);
        btn_Refresh=findViewById(R.id.btn_Refresh);
        btn_Refresh.setOnClickListener(this);
        btn_find=findViewById(R.id.btn_find);
        btn_find.setOnClickListener(this);
        btn_Return=findViewById(R.id.btn_Return);
        btn_Return.setOnClickListener(this);
        orderList=findViewById(R.id.orderList);
        orderList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                try {
                    view.setSelected(true);
                    selOrderNo=orderJson.optJSONObject(i).getString("OrderNo");
                    selStyleSort=orderJson.optJSONObject(i).getString("StyleSort");
                    Intent intent = new Intent();
                    intent.putExtra("OrderNo",selOrderNo);
                    intent.putExtra("StyleSort",selStyleSort);
                    setResult(1001,intent);
                    finish();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        arrangeList =findViewById(R.id.arrangeList);
        arrangeList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                try {
                    view.setSelected(true);
                    selOrderNo=arrangeJson.optJSONObject(i).getString("OrderNo");
                    selStyleSort=arrangeJson.optJSONObject(i).getString("StyleSort");
                    Intent intent = new Intent();
                    intent.putExtra("OrderNo",selOrderNo);
                    intent.putExtra("StyleSort",selStyleSort);
                    setResult(1001,intent);
                    finish();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        ((Button)findViewById(R.id.view_Btn0)).setOnClickListener(this);
        ((Button)findViewById(R.id.view_Btn1)).setOnClickListener(this);
        ((Button)findViewById(R.id.view_Btn2)).setOnClickListener(this);
        ((Button)findViewById(R.id.view_Btn3)).setOnClickListener(this);
        ((Button)findViewById(R.id.view_Btn4)).setOnClickListener(this);
        ((Button)findViewById(R.id.view_Btn5)).setOnClickListener(this);
        ((Button)findViewById(R.id.view_Btn6)).setOnClickListener(this);
        ((Button)findViewById(R.id.view_Btn7)).setOnClickListener(this);
        ((Button)findViewById(R.id.view_Btn8)).setOnClickListener(this);
        ((Button)findViewById(R.id.view_Btn9)).setOnClickListener(this);
        ((Button)findViewById(R.id.view_Btn0)).setOnClickListener(this);
        ((Button)findViewById(R.id.view_Btnfh)).setOnClickListener(this);
        ((Button)findViewById(R.id.view_BtnA)).setOnClickListener(this);
        ((Button)findViewById(R.id.view_BtnB)).setOnClickListener(this);
        ((Button)findViewById(R.id.view_BtnC)).setOnClickListener(this);
        ((Button)findViewById(R.id.view_BtnD)).setOnClickListener(this);
        ((Button)findViewById(R.id.view_BtnE)).setOnClickListener(this);
        ((Button)findViewById(R.id.view_BtnF)).setOnClickListener(this);
        ((Button)findViewById(R.id.view_BtnG)).setOnClickListener(this);
        ((Button)findViewById(R.id.view_BtnH)).setOnClickListener(this);
        ((Button)findViewById(R.id.view_BtnI)).setOnClickListener(this);
        ((Button)findViewById(R.id.view_BtnJ)).setOnClickListener(this);
        ((Button)findViewById(R.id.view_BtnK)).setOnClickListener(this);
        ((Button)findViewById(R.id.view_BtnL)).setOnClickListener(this);
        ((Button)findViewById(R.id.view_BtnM)).setOnClickListener(this);
        ((Button)findViewById(R.id.view_BtnN)).setOnClickListener(this);
        ((Button)findViewById(R.id.view_BtnO)).setOnClickListener(this);
        ((Button)findViewById(R.id.view_BtnP)).setOnClickListener(this);
        ((Button)findViewById(R.id.view_BtnQ)).setOnClickListener(this);
        ((Button)findViewById(R.id.view_BtnR)).setOnClickListener(this);
        ((Button)findViewById(R.id.view_BtnS)).setOnClickListener(this);
        ((Button)findViewById(R.id.view_BtnT)).setOnClickListener(this);
        ((Button)findViewById(R.id.view_BtnU)).setOnClickListener(this);
        ((Button)findViewById(R.id.view_BtnV)).setOnClickListener(this);
        ((Button)findViewById(R.id.view_BtnW)).setOnClickListener(this);
        ((Button)findViewById(R.id.view_BtnX)).setOnClickListener(this);
        ((Button)findViewById(R.id.view_BtnY)).setOnClickListener(this);
        ((Button)findViewById(R.id.view_BtnZ)).setOnClickListener(this);
        ((Button)findViewById(R.id.view_BtnDel)).setOnClickListener(this);
        ((Button)findViewById(R.id.view_BtnDel)).setOnLongClickListener(this);

    }


    @Override
    protected void onStart() {
        super.onStart();
        edt_OrderNO.requestFocus();
        edt_OrderNO.requestFocusFromTouch();
        getArrange();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_Refresh:
                searchBarcodeData("","");
                break;
            case R.id.btn_find:
                searchBarcodeData(edt_barcode.getText().toString(),edt_OrderNO.getText().toString());
                break;
            case R.id.btn_Affirm:
                //返回
                Intent intent = new Intent();
                intent.putExtra("selOrderNo",selOrderNo);
                intent.putExtra("selStyleSort",selStyleSort);
                setResult(1001,intent);
                finish();

                break;
            case R.id.btn_Return:
                finish();
                break;
            case R.id.view_Btn0:
            case R.id.view_Btn1:
            case R.id.view_Btn2:
            case R.id.view_Btn3:
            case R.id.view_Btn4:
            case R.id.view_Btn5:
            case R.id.view_Btn6:
            case R.id.view_Btn7:
            case R.id.view_Btn8:
            case R.id.view_Btn9:
            case R.id.view_BtnA:
            case R.id.view_BtnB:
            case R.id.view_BtnC:
            case R.id.view_BtnD:
            case R.id.view_BtnE:
            case R.id.view_BtnF:
            case R.id.view_BtnG:
            case R.id.view_BtnH:
            case R.id.view_BtnI:
            case R.id.view_BtnJ:
            case R.id.view_BtnK:
            case R.id.view_BtnL:
            case R.id.view_BtnM:
            case R.id.view_BtnN:
            case R.id.view_BtnO:
            case R.id.view_BtnP:
            case R.id.view_BtnQ:
            case R.id.view_BtnR:
            case R.id.view_BtnS:
            case R.id.view_BtnT:
            case R.id.view_BtnU:
            case R.id.view_BtnV:
            case R.id.view_BtnW:
            case R.id.view_BtnX:
            case R.id.view_BtnY:
            case R.id.view_BtnZ:
            case R.id.view_Btnfh:
                Button tmpBtn1 = (Button) view.findViewById(view.getId());
                if (tmpEdit!=null) {
                    ((EditText) tmpEdit).getText().append(tmpBtn1.getText());
                }
                break;
            case R.id.view_BtnDel:
                if (tmpEdit!=null) {
                    if (((EditText) tmpEdit).getText().length() > 0) {
                        ((EditText) tmpEdit).setSelection(((EditText) tmpEdit).getText().length());
                        int start = ((EditText) tmpEdit).getSelectionStart();
                        ((EditText) tmpEdit).getText().delete(start - 1, start);
                    }
                }
                break;
            default:
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }
    //直接连获取数据，与Handler配套使用;
    private void ReadSQLData(final String SQLComm) {
        System.out.println("SQLComm:"+SQLComm);
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try{
                    JSONArray jsonArray  = DBUtil.QuerySQL2JSON(SQLComm);
                    System.out.println(jsonArray);
                    //往界面转数据;
                    if ((jsonArray!=null)&&(jsonArray.length()>0)) {
                        String OPERTYPE="";
                        if (jsonArray.optJSONObject(0).has("OPERTYPE")==true) OPERTYPE=jsonArray.optJSONObject(0).getString("OPERTYPE");
                        if (jsonArray.optJSONObject(0).has("OperType")==true) OPERTYPE=jsonArray.optJSONObject(0).getString("OperType");
                        if (OPERTYPE.toUpperCase().equals("STYLEINFO")) {
                            orderJson=jsonArray;
                            //显示预排单;
                            Message msg = new Message();
                            msg.what = MSG_OrderOver;
                            handler.removeMessages(msg.what);
                            handler.sendMessage(msg);
                        }
                        //返回的为订单数据;
                        if (OPERTYPE.equals("GetArrange")==true)
                        {
                            Log.d("msg","GetSelectOrder--------------------2");
                            arrangeJson=jsonArray;
                            //显示预排单;
                            Message msg = new Message();
                            msg.what = MSG_GetArrangeOver;
                            handler.removeMessages(msg.what);
                            handler.sendMessage(msg);
                        }

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

        };
        new Thread(run).start();

    }


    //通过消息来执行处理类程序,不更新UI则不一定需要通过这个;
    final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            // TODO Auto-generated method stub
            // 根据消息ID来判断要做的事情
            int msgId = msg.what;
            switch (msgId) {

                case MSG_OrderOver:
                    //显示明细数据
                    OrderListAdapter orderListAdapter=new OrderListAdapter(getApplicationContext());
                    orderList.setAdapter(orderListAdapter);
                    break;

                case MSG_GetArrangeOver:
                    //显示明细数据
                    ArrangeListAdapter arrangeListAdapter=new ArrangeListAdapter(getApplicationContext());
                    arrangeList.setAdapter(arrangeListAdapter);
                    break;
                default:
                    break;
            }
        }
    };


    //工序表格适配器;
    public final class ArrangeListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public ArrangeListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return arrangeJson.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return arrangeJson.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) convertView = inflater.inflate(R.layout.activity_styleinfo_styleitem, null, false);
            convertView.setBackground(getResources().getDrawable(R.drawable.orderlist_selector));
            int ct_max_background = getResources().getColor(R.color.ct_max_background);
            int ct_nor_background = getResources().getColor(R.color.ct_nor_background);
            int textColor=getResources().getColor(R.color.text_black);
            try {
                Log.d("msg","getView()----------------------------------------------------->"+position);
                TextView tv = (TextView) convertView.findViewById(R.id.text_proc_workdate);// 显示文字
                if (arrangeJson.optJSONObject(position).has("WorkDate")) {
                    tv.setText(arrangeJson.optJSONObject(position).get("WorkDate").toString());
                    tv.setTextColor(textColor);
                }
                if (arrangeJson.optJSONObject(position).has("OrderNo")) {
                    tv = (TextView) convertView.findViewById(R.id.text_proc_orderno);// 显示文字
                    tv.setText(arrangeJson.optJSONObject(position).get("OrderNo").toString());
                    tv.setTextColor(textColor);
                }
                if (arrangeJson.optJSONObject(position).has("StyleNo")) {
                    tv = (TextView) convertView.findViewById(R.id.text_proc_styleno);// 显示文字
                    tv.setText(arrangeJson.optJSONObject(position).get("StyleNo").toString());
                    tv.setTextColor(textColor);
                }
                if (arrangeJson.optJSONObject(position).has("StyleSort")) {
                    tv = (TextView) convertView.findViewById(R.id.text_proc_stylesort);// 显示文字
                    tv.setText(arrangeJson.optJSONObject(position).get("StyleSort").toString());
                    tv.setTextColor(textColor);
                }
                if (arrangeJson.optJSONObject(position).has("State")) {
                    tv = (TextView) convertView.findViewById(R.id.text_proc_state);// 显示文字
                    tv.setText(arrangeJson.optJSONObject(position).get("State").toString());
                    tv.setTextColor(textColor);
                }

            } catch (JSONException e) {
                e.printStackTrace();

            }
            Log.d("msg","ArrangeListAdapter_position:"+position);
            return convertView;
        }
    }


    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus) {
            v.setBackgroundColor(getResources().getColor(R.color.skyblue));
            tmpEdit=v;
        }
        else v.setBackgroundColor(0);
    }

    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected void hideBottomUIMenu() {
        //隐藏状态栏和底部虚拟按键
        View decorView = getWindow().getDecorView();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            int flag = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
            decorView.setSystemUiVisibility(flag);
        }
    }

    @Override
    public boolean onLongClick(View view) {
        switch (view.getId()){
            case R.id.view_BtnDel:
                if (tmpEdit!=null) {
                    ((EditText) tmpEdit).setText("");
                }
                break;
            default:
                break;
        }
        return false;
    }

    //订单表格适配器;
    public final class OrderListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public OrderListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return orderJson.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return orderJson.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = inflater.inflate(R.layout.activity_styleinfo_listhead, null, false);
            int pullVatListWidth=parent.getWidth();
            //view.setLayoutParams(new ListView.LayoutParams(pullVatListWidth,38));
            int color = getResources().getColor(R.color.text_black);
            String tmpValue;
            try {
                Log.d("msg", "getView()a----------------------------------------------------->" + position);
                Log.d(TAG, "getView()----------------------------------------------------->" + position);
                if (orderJson.optJSONObject(position).has("ConColor") == true) {
                    tmpValue = orderJson.optJSONObject(position).getString("ConColor");
                    color=GetColorValue(tmpValue);
                }
                if ((orderJson.optJSONObject(position).has("ManuDepart") == true)&&(view.findViewById(R.id.item_ManuDepart)!=null)) {
                    ((TextView) view.findViewById(R.id.item_ManuDepart)).setText(orderJson.optJSONObject(position).getString("ManuDepart"));
                    ((TextView) view.findViewById(R.id.item_ManuDepart)).setTextColor(color);
                }
                if ((orderJson.optJSONObject(position).has("OrderNo") == true)&&(view.findViewById(R.id.item_OrderNo)!=null)) {
                    ((TextView) view.findViewById(R.id.item_OrderNo)).setText(orderJson.optJSONObject(position).getString("OrderNo"));
                    ((TextView) view.findViewById(R.id.item_OrderNo)).setTextColor(color);
                }
                if ((orderJson.optJSONObject(position).has("StyleSort") == true)&&(view.findViewById(R.id.item_StyleSort)!=null)) {
                    ((TextView) view.findViewById(R.id.item_StyleSort)).setText(orderJson.optJSONObject(position).getString("StyleSort"));
                    ((TextView) view.findViewById(R.id.item_StyleSort)).setTextColor(color);
                }

            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            Log.d("msg","OrderListAdapter_position:"+position);
            return view;
        }
    }


    //判断是否为数字
    public static boolean isNumer(String str) {
        Pattern pattern = Pattern.compile("-?[0-9]+\\.?[0-9]+");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }
    //从字符串转颜色
    private int GetColorValue(String paramColor){
        int PenColor= Color.WHITE;
        String StrPenColor=paramColor;
        if ((StrPenColor.indexOf("#")==0)&&(StrPenColor.length()==7)){
            int testColor=Integer.parseInt(StrPenColor.substring(1),16);
            int red = (testColor & 0xff0000) >> 16;
            int green = (testColor & 0x00ff00) >> 8;
            int blue = (testColor & 0x0000ff);
            PenColor=Color.rgb(red, green, blue);
        }else {
            if (isNumer(StrPenColor)) {
                int testColor = Integer.parseInt(StrPenColor);
                int red = (testColor & 0xff0000) >> 16;
                int green = (testColor & 0x00ff00) >> 8;
                int blue = (testColor & 0x0000ff);
                PenColor = Color.rgb(red, green, blue);
            } else {
                if (StrPenColor.equals("Black") == true)
                    PenColor = Color.BLACK;
                if (StrPenColor.equals("Blue") == true)
                    PenColor = Color.BLUE;
                if (StrPenColor.equals("Yellow") == true)
                    PenColor = Color.YELLOW;
                if (StrPenColor.equals("Red") == true)
                    PenColor = Color.RED;
                if (StrPenColor.equals("Green") == true)
                    PenColor = Color.GREEN;
                if (StrPenColor.equals("Gray") == true)
                    PenColor = Color.LTGRAY;
                if (StrPenColor.equals("White") == true)
                    PenColor = Color.WHITE;
            }
        }
        return PenColor;
    }


}
